package com.anita.member.application.service;

import com.anita.member.application.command.MemberUpdatePasswordCommand;
import com.anita.member.application.port.in.MemberUpdatePasswordUseCase;
import com.anita.member.common.enums.Resp;
import com.anita.member.common.exception.BusinessException;
import com.anita.member.domain.model.member.*;
import com.anita.member.domain.repository.MemberRepository;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author qiu
 * @date 2025/10/21
 * @description
 */
@Slf4j
@Service
@Transactional
public class MemberUpdatePasswordService implements MemberUpdatePasswordUseCase {

    @Resource
    private MemberRepository memberRepository;

    @Resource
    private PasswordEncoder passwordEncoder;

    /**
     * 更新会员密码
     * @param command
     */
    @Override
    public void updatePassword(MemberUpdatePasswordCommand command) {
        Optional<Member> memberOptional = memberRepository.findById(MemberId.of(command.id()));
        if (memberOptional.isEmpty()){
            throw new BusinessException(Resp.USER_NOT_FOUND);
        }

        Member member = memberOptional.get();

        //修改密码
        member.changePassword(command.oldPassword(), command.newPassword(), passwordEncoder);

        //保存更新
        memberRepository.save(member);

        log.info("会员更新密码成功: {}", member.getUserName().value());
    }
}
